<?php

namespace addons\facrm\controller\facrm\customer;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;
use think\exception\PDOException;


/**
 * 客户跟进记录
 */
class Record extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'content';
    protected $childrenAdminIds = [];
    private $types = "customer";
    protected $noNeedRight = ['getRecordTypeList','signin'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Record');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 跟进记录
     */
    public function index()
    {
        $customer_id = $this->request->post("customer_id");
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'contacts')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];


        $filter_w['types'] = $this->types;
        if ($customer_id) {
            $filter_w['types_id'] = $customer_id;
            if (!$this->auth->checkCustomerAuth($customer_id, $this->auth)) {
                $this->error(__('您没有权限'));
            }
        }else{
            $filter_w['create_user_id'] = $this->auth->id;
            if (isset($filter['scene_id'])) {
                if (!isset($scene_list[$filter['scene_id']])) {
                    $this->error(__("您没有权限"));
                }
                $filter_w['create_user_id'] = $this->auth->id;
                switch ($filter['scene_id']) {
                    case 4:
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                        $filter_w['create_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    case 5:
                        //我的
                        $filter_w['create_user_id'] = $this->auth->id;
                        break;
                    case 6:
                        //下属
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                        $filter_w['create_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    default://其它的还做TODO
                        $filter_w['create_user_id'] = $this->auth->id;

                }
            }
        }
        unset($filter['scene_id']);
        $this->request->get(['filter' => json_encode($filter)]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($filter_w)
            ->where($where)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
                'files' => function ($files) {
                    $files->field('id,url,record_id');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $this->addon_config = get_addon_config('facrm');
        $lists=array();
        foreach ($list as $row){
            $record_type_text= $row->record_type_text;
            $lists[]=array_merge($row->toArray(),['record_type_text'=>$record_type_text]);//获取器失效
        }

        $result = array("rows" => $lists);

        return $this->success('', $result);


    }

    /**
     * 获取跟进类型
     * @ApiInternal
     */
    public function getRecordTypeList()
    {
        $config = get_addon_config('facrm');
        return $this->success('', $config['record_type']);
    }



    /**
     * 添加跟进
     * @return mixed
     */
    public function add()
    {
        if (!$this->request->isPost())
            $this->error(__("提交方式有误"));
        $customer_id = $this->request->post("customer_id");
        if (!$customer_id)
            $this->error(__("客户不能为空"));

        $customer = model('\app\admin\model\facrm\Customer');
        $row = $customer->get($customer_id);
        if (!$row)
            $this->error(__('No Results were found'));

        if (!$this->auth->checkCustomerAuth($row, $this->auth)) {
            $this->error(__('您没有权限1'));
        }
        $params = $this->request->post("row/a");
        $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : 0;

        $params = array_merge($params, [
            'create_user_id' => $this->auth->id,
            'types_id' => $row->id,
            'types' => $this->types,
        ]);

        $name = str_replace("\\model\\", "\\validate\\", get_class( $this->model));
        $result = $this->model->allowField(true)->validateFailException(false)->validate($name . '.add')->save($params);
        if ($result){
            //更新客户表
            $row->next_time = $params['next_time'];
            $row->follow_time = time();
            $row->save();
            //如果存在附件
            if (isset($params['image'])&&$params['image']) {
                $images = explode(",", $params['image']);
                $files_data = array();
                foreach ($images as $key => $v) {
                    $files_data[$key]['url'] = $v;
                    $files_data[$key]['types_id'] = $row->id;
                    $files_data[$key]['types'] = $this->types;
                }
                $this->model->files()->saveAll($files_data);
            }
        }else{
            $this->error(__($this->model->getError()));
        }

        return $this->success(__('跟进成功'));
    }


    /**
     * 外访签到跟进
     * @ApiMethod (POST)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户ID")
     * @ApiParams(name="lng", type="string", required=true, description="经度")
     * @ApiParams(name="lat", type="string", required=true, description="维度")
     * @ApiParams(name="image", type="string", required=false, description="图片附件多个逗号隔开")
     * @ApiParams(name="content", type="string", required=true, description="跟进内容")
     * @ApiParams(name="position", type="string", required=false, description="定位地址【预留】")
     * @return mixed
     */
    public function signin()
    {
        if (!$this->request->isPost())
            $this->error(__("提交方式有误"));
        $customer_id = $this->request->post("customer_id");
        if (!$customer_id)
            $this->error(__("客户不能为空"));

        $customer = model('\app\admin\model\facrm\Customer');
        $row = $customer->get($customer_id);
        if (!$row)
            $this->error(__('No Results were found'));

        if (!$this->auth->checkCustomerAuth($row, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        $params = $this->request->post();
        if (!isset($params['content'])||!$params['content']){
            $this->error(__('内容不能为空'));
        }
        $params['content'].="<br />{$params['position']}";//把位置也输入到内容里面去
        $params = array_merge($params, [
            'create_user_id' => $this->auth->id,
            'types_id' => $row->id,
            'record_type'=>'2',//2是上门拜访
            'types' => $this->types,
        ]);


        //判断经度/^[\-\+]?(0(\.\d{1,8})?|([1-9](\d)?)(\.\d{1,11})?|1[0-7]\d{1}(\.\d{1,11})?|180(([.][0]{1,11})?))$/
        if(!isset($params['lng'])||!(intval(abs($params['lng'])>=0&&intval(abs($params['lng']))<180))){
            $this->error(__('定位有误g'));
        }
        //判断维度preg_match("/^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/", $params['lat'])
        if(!isset($params['lat'])||!(intval(abs($params['lat'])>=0&&intval(abs($params['lat']))<90))){
            $this->error(__('定位有误a'));
        }

        $name = str_replace("\\model\\", "\\validate\\", get_class( $this->model));
        $result = $this->model->allowField(true)->validateFailException(false)->validate($name . '.add')->save($params);
        if ($result){
            //更新客户表
            if (!$row->lng&&!$row->lat){
                $row->lng=$params['lng'];
                $row->lat=$params['lat'];
            }
            $row->follow_time = time();
            $row->save();
            //如果存在附件
            if (isset($params['image'])&&$params['image']) {
                $images = explode(",", $params['image']);
                $files_data = array();
                foreach ($images as $key => $v) {
                    $files_data[$key]['url'] = $v;
                    $files_data[$key]['types_id'] = $row->id;
                    $files_data[$key]['types'] = $this->types;
                }
                $this->model->files()->saveAll($files_data);
            }
        }else{
            $this->error(__($this->model->getError()));
        }
        //判断是否是改数据提交伪造。
        $cachekey=md5("{$params['lat']},{$params['lng']}");
        $result=cache($cachekey);
        if (!$result||!isset($result['result']['address'])||$result['result']['address']!=$params['position']){
           \think\Log::write("______签到地址有可能是伪造的______".$this->auth->id);
        }
        return $this->success(__('签到成功'));
    }




    /**
     * 删除
     * @param string $id
     */
    public function del()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $pk = $this->model->getPk();
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $list = $this->model->where($pk, 'in', $id)->where('create_user_id', 'in', $this->childrenAdminIds)->select();


        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 附件查看
     */
    public function files($ids = "")
    {

        $customer_id = $this->request->param("customer_id");
        $filter_w['types'] = $this->types;
        if (!$customer_id) {
            $this->error(__('客户不存在'));
        }
        $filter_w['types_id'] = $customer_id;
        if (!$this->auth->checkCustomerAuth($customer_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        $this->model = model('\app\admin\model\facrm\record\Files');
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
        foreach ($list as $k => &$v) {
            $v['fullurl'] = cdnurl($v['url']);
            $v['imagetype'] = pathinfo($v['url'], PATHINFO_EXTENSION);
        }
        unset($v);
        $result = array("rows" => $list);
        return $this->success('',$result);
    }

}
